<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Redis 框架测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        .section {
            border: 1px solid #ddd;
            padding: 15px;
            border-radius: 5px;
        }
        .log {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #ccc;
            padding: 10px;
            margin-top: 10px;
            background-color: #f5f5f5;
            font-family: monospace;
            font-size: 12px;
        }
        button {
            margin: 5px;
            padding: 8px 15px;
            cursor: pointer;
        }
        .connected { color: green; }
        .disconnected { color: red; }
        input {
            margin: 5px;
            padding: 5px;
        }
    </style>
</head>
<body>
    <h1>WebSocket Redis 框架测试页面</h1>
    
    <div class="container">
        <div class="section">
            <h2>WebSocket 连接</h2>
            <div>
                状态: <span id="status" class="disconnected">未连接</span>
            </div>
            <button onclick="connect()">连接</button>
            <button onclick="disconnect()">断开</button>
            <button onclick="sendHeartbeat()">发送心跳</button>
            
            <h3>订阅管理</h3>
            <button onclick="subscribe('DEVICE_STATUS')">订阅设备状态</button>
            <button onclick="subscribe('ALARM')">订阅报警信息</button>
            <button onclick="subscribe('SYSTEM_NOTIFY')">订阅系统通知</button>
            <button onclick="subscribe('USER_MESSAGE')">订阅用户消息</button>
            <br>
            <button onclick="subscribe('SENSOR_DATA')">订阅传感器数据</button>
            <button onclick="subscribe('ORDER_STATUS')">订阅订单状态</button>
            <button onclick="subscribe('INVENTORY_CHANGE')">订阅库存变化</button>
            <br>
            <button onclick="unsubscribe('DEVICE_STATUS')">取消设备状态</button>
            <button onclick="unsubscribe('ALARM')">取消报警信息</button>
            <button onclick="clearAll()">清除所有订阅</button>
            <br>
            <button onclick="getSubscriptionTypes()">查看订阅类型</button>
            <button onclick="getStatus()">查看连接状态</button>
            
            <h3>消息日志</h3>
            <div id="wsLog" class="log"></div>
        </div>
        
        <div class="section">
            <h2>模拟业务操作</h2>
            
            <h3>更新设备状态</h3>
            <div>
                设备ID: <input type="text" id="deviceId" value="device001">
                在线状态: <select id="online">
                    <option value="true">在线</option>
                    <option value="false">离线</option>
                </select>
                温度: <input type="number" id="temperature" value="25.5">
                <button onclick="updateDeviceStatus()">更新</button>
            </div>
            
            <h3>发送报警</h3>
            <div>
                设备ID: <input type="text" id="alarmDeviceId" value="device001">
                报警类型: <input type="text" id="alarmType" value="TEMPERATURE_HIGH">
                消息: <input type="text" id="alarmMessage" value="温度过高">
                <button onclick="sendAlarm()">发送报警</button>
            </div>
            
            <h3>更新传感器数据</h3>
            <div>
                传感器ID: <input type="text" id="sensorId" value="sensor001">
                类型: <select id="sensorType">
                    <option value="temperature">温度</option>
                    <option value="humidity">湿度</option>
                    <option value="pressure">气压</option>
                    <option value="light">光照</option>
                    <option value="co2">CO2</option>
                </select>
                数值: <input type="number" id="sensorValue" value="25.5" step="0.1">
                <button onclick="updateSensorData()">更新</button>
            </div>
            
            <h3>API 调用日志</h3>
            <div id="apiLog" class="log"></div>
        </div>
    </div>

    <script>
        let ws = null;
        
        function log(message, target = 'wsLog') {
            const logDiv = document.getElementById(target);
            const time = new Date().toLocaleTimeString();
            logDiv.innerHTML += `[${time}] ${message}\n`;
            logDiv.scrollTop = logDiv.scrollHeight;
        }
        
        function connect() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                log('已经连接');
                return;
            }
            
            ws = new WebSocket('ws://localhost:8080/ws');
            
            ws.onopen = function() {
                document.getElementById('status').textContent = '已连接';
                document.getElementById('status').className = 'connected';
                log('WebSocket 连接成功');
                // 启动心跳
                startHeartbeat();
            };
            
            ws.onmessage = function(event) {
                const message = JSON.parse(event.data);
                
                // 根据不同的命令类型处理消息
                switch(message.command) {
                    case 'PUSH':
                        // 数据推送
                        log(`[推送-${message.topic}] ${message.key}:`);
                        log(JSON.stringify(message.response, null, 2));
                        break;
                    
                    case 'CONNECTED':
                        // 连接成功
                        log(`连接成功: ${message.response.message}`);
                        log(`客户端ID: ${message.response.clientId}`);
                        break;
                    
                    case 'SUBSCRIBED':
                        // 订阅成功
                        log(`订阅成功: ${message.topic || message.response.type}`);
                        break;
                    
                    case 'UNSUBSCRIBED':
                        // 取消订阅成功
                        log(`取消订阅: ${message.topic || message.params}`);
                        break;
                    
                    case 'HEARTBEAT_ACK':
                        // 心跳响应
                        log(`心跳响应: ${new Date(message.response.timestamp).toLocaleTimeString()}`);
                        break;
                    
                    case 'ERROR':
                        // 错误消息
                        log(`错误: ${message.response.error}`);
                        break;
                    
                    case 'CLEARED':
                        // 清除订阅
                        log(`${message.response.message}`);
                        break;
                    
                    case 'SUBSCRIPTION_TYPES':
                        // 订阅类型列表
                        log('可用订阅类型:');
                        log(JSON.stringify(message.response, null, 2));
                        break;
                    
                    case 'STATUS':
                        // 连接状态
                        log('连接状态:');
                        log(JSON.stringify(message.response, null, 2));
                        break;
                    
                    default:
                        // 其他消息
                        log('收到消息: ' + JSON.stringify(message, null, 2));
                }
            };
            
            ws.onclose = function() {
                document.getElementById('status').textContent = '未连接';
                document.getElementById('status').className = 'disconnected';
                log('WebSocket 连接关闭');
                // 停止心跳
                stopHeartbeat();
            };
            
            ws.onerror = function(error) {
                log('WebSocket 错误: ' + error);
            };
        }
        
        function disconnect() {
            if (ws) {
                ws.close();
            }
        }
        
        function sendMessage(command, params = null, topic = null) {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                log('WebSocket 未连接');
                return;
            }
            
            const message = {
                command: command,
                topic: topic,
                params: params
            };
            
            ws.send(JSON.stringify(message));
            log('发送消息: ' + JSON.stringify(message));
        }
        
        function sendHeartbeat() {
            sendMessage('HEARTBEAT');
        }
        
        function subscribe(type) {
            sendMessage('SUBSCRIBE', null, type);
        }
        
        function unsubscribe(type) {
            sendMessage('UNSUBSCRIBE', null, type);
        }
        
        function clearAll() {
            sendMessage('CLEAR');
        }
        
        function getSubscriptionTypes() {
            sendMessage('LIST');
        }
        
        function getStatus() {
            sendMessage('STATUS');
        }
        
        // API 调用函数
        async function updateDeviceStatus() {
            const deviceId = document.getElementById('deviceId').value;
            const online = document.getElementById('online').value;
            const temperature = document.getElementById('temperature').value;
            
            try {
                const response = await fetch(`/test/device/${deviceId}/status?online=${online}&temperature=${temperature}`, {
                    method: 'POST'
                });
                const data = await response.json();
                log('更新设备状态: ' + JSON.stringify(data, null, 2), 'apiLog');
            } catch (error) {
                log('更新失败: ' + error, 'apiLog');
            }
        }
        
        async function sendAlarm() {
            const deviceId = document.getElementById('alarmDeviceId').value;
            const alarmType = document.getElementById('alarmType').value;
            const message = document.getElementById('alarmMessage').value;
            
            try {
                const response = await fetch(`/test/alarm/send?deviceId=${deviceId}&alarmType=${alarmType}&message=${message}`, {
                    method: 'POST'
                });
                const data = await response.json();
                log('发送报警: ' + JSON.stringify(data, null, 2), 'apiLog');
            } catch (error) {
                log('发送失败: ' + error, 'apiLog');
            }
        }
        
        async function updateSensorData() {
            const sensorId = document.getElementById('sensorId').value;
            const type = document.getElementById('sensorType').value;
            const value = document.getElementById('sensorValue').value;
            
            try {
                const response = await fetch(`/api/sensor/${sensorId}/data?type=${type}&value=${value}`, {
                    method: 'POST'
                });
                const data = await response.json();
                log('更新传感器数据: ' + JSON.stringify(data, null, 2), 'apiLog');
            } catch (error) {
                log('更新失败: ' + error, 'apiLog');
            }
        }
        
        // 心跳定时器
        let heartbeatInterval = null;
        
        // 启动心跳
        function startHeartbeat() {
            // 清除旧的定时器
            if (heartbeatInterval) {
                clearInterval(heartbeatInterval);
            }
            
            // 每30秒发送一次心跳
            heartbeatInterval = setInterval(() => {
                if (ws && ws.readyState === WebSocket.OPEN) {
                    sendHeartbeat();
                    log('自动发送心跳');
                }
            }, 30000);
        }
        
        // 停止心跳
        function stopHeartbeat() {
            if (heartbeatInterval) {
                clearInterval(heartbeatInterval);
                heartbeatInterval = null;
            }
        }
        
        // 自动连接
        window.onload = function() {
            connect();
        };
    </script>
</body>
</html>